package com.funtonow.jqdk.fkcs.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.BankCardParams;
import com.baidu.ocr.sdk.model.BankCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.bean.IdCardAndBankInfo;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.event.UserInfoEvent;
import com.funtonow.jqdk.ui.ExamineFailActivity;
import com.funtonow.jqdk.ui.LoginActivity;
import com.funtonow.jqdk.ui.UserInfoActivity;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.FileUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.HttpUtil2;
import com.funtonow.jqdk.utils.LogUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StringUtil;
import com.funtonow.jqdk.utils.ToastUtils;
import com.funtonow.jqdk.widget.ProgressDialogUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.utils.LogUtils;
import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.BIND_BANK_CARD;
import static com.funtonow.jqdk.base.UrlUtils.GET_BANK_SMS;
import static com.funtonow.jqdk.base.UrlUtils.GET_SMS;
import static com.funtonow.jqdk.base.UrlUtils.OCR_BANK_CARD;
import static com.funtonow.jqdk.base.UrlUtils.UPDATE;

/**
 * @author Jiajien
 * @date 2019/7/16
 */
public class BankActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.et_bank_num)
    EditText etBankNum;
    @BindView(R.id.et_bank_name)
    EditText etEtBankName;
    @BindView(R.id.et_bank_phone)
    EditText etBankPhone;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.et_sms)
    EditText etSms;
    @BindView(R.id.btn_bank_card)
    Button btnBankCard;
    @BindView(R.id.iv_bank_card)
    ImageView ivBackCard;

    private static final int REQUEST_CODE_BANKCARD = 111;

    private UserInfoBean userInfoBean;
    private CountDownTimer timer;

    private String bindOrderId;

    @Override
    public int getLayoutRes() {
        return R.layout.fk_activity_bank;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar("绑定银行卡");
        initAccessTokenWithAkSk();
        userInfoBean = SPUtil.getUserInfo();
        assert userInfoBean != null;
        tvName.setText(userInfoBean.getNickname());
        etBankPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!StringUtil.isEmpty(s.toString()) && s.length() == 11
                        && !StringUtil.isEmpty(etBankNum.getText().toString())
                        && !StringUtil.isEmpty(etBankPhone.getText().toString())) {
                    tvSendCode.setEnabled(true);
                    tvSendCode.setTextColor(getResources().getColor(R.color.color_333333));
                } else {
                    tvSendCode.setEnabled(false);
                    tvSendCode.setTextColor(getResources().getColor(R.color.color_c7c7cc));
                }
            }
        });
        etSms.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!StringUtil.isEmpty(s.toString()) && etBankPhone.getText().toString().length() == 11
                        && !StringUtil.isEmpty(etBankNum.getText().toString())
                        && !StringUtil.isEmpty(etBankPhone.getText().toString())
                        && !StringUtil.isEmpty(s.toString())) {
                    btnBankCard.setEnabled(true);
                    btnBankCard.setBackgroundResource(R.drawable.btn_blue_layout);
                } else {
                    btnBankCard.setEnabled(false);
                    btnBankCard.setBackgroundResource(R.drawable.btn_gray_layout);
                }
            }
        });
    }


    @OnClick({R.id.iv_bank_card, R.id.tv_send_code, R.id.btn_bank_card})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_bank_card:
                Intent intent = new Intent(this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtils.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                        CameraActivity.CONTENT_TYPE_BANK_CARD);
                startActivityForResult(intent, REQUEST_CODE_BANKCARD);
                break;
            case R.id.tv_send_code:
                //getBankSms();
                getSms(etBankPhone.getText().toString(),"","");
                break;
            case R.id.btn_bank_card:
                bindBankCard();
                updateInfo();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String filePath = data.getStringExtra(CameraActivity.KEY_OUTPUT_FILE_PATH);
                ProgressDialogUtil.startProgressDialog(this);
                recBankCard(this, filePath);
//                if (AppUtils.getAppName(this).equals(getResources().getString(R.string.ssq_app_name))) {
//                    recBankCard(this, filePath);
//                } else {
//                    ocrBankCard(filePath);
//                }
            }
        }
    }

    /**
     * 百度ocr
     *
     * @param ctx
     * @param filePath
     */
    private void recBankCard(Context ctx, String filePath) {
        BankCardParams param = new BankCardParams();
        param.setImageFile(new File(filePath));
        OCR.getInstance(ctx).recognizeBankCard(param, new OnResultListener<BankCardResult>() {
            @Override
            public void onResult(BankCardResult result) {
                ProgressDialogUtil.stopProgressDialog();
                String res = String.format("卡号：%s\n类型：%s\n发卡行：%s",
                        result.getBankCardNumber(),
                        result.getBankCardType().name(),
                        result.getBankName());
                LogUtil.i(res + "  ");
                if (result.getBankCardType().name().equals(BankCardResult.BankCardType.Debit.name())) {
                    etBankNum.setText(result.getBankCardNumber());
                    etEtBankName.setText(result.getBankName());
                } else if (result.getBankCardType().name().equals(BankCardResult.BankCardType.Unknown.name())) {
                    etBankNum.setText(result.getBankCardNumber());
                } else {
                    ToastUtils.show("请使用借记卡");
                }
            }

            @Override
            public void onError(OCRError error) {

            }
        });
    }

    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();

            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                LogUtil.i("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(), Constants.AI_APP_KEY, Constants.AI_SECRET_KEY);
    }


    /**
     * 获取验证码
     */
    public void getBankSms() {
        ProgressDialogUtil.startProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("openid", userInfoBean.getOpenid());
        params.put("token", userInfoBean.getToken());
        params.put("appid", Constants.DATA_APP_ID);
        params.put("bankCardNo", etBankNum.getText().toString());
        params.put("bankName", etEtBankName.getText().toString());
        params.put("idCardNo", userInfoBean.getShenfenz());
        params.put("mobile", etBankPhone.getText().toString());
        params.put("name", tvName.getText().toString());
        HttpUtil.getInstance().postDataAsynToNet(GET_BANK_SMS, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                LogUtil.i(jsonString + " ************** getBankSms ");
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") == 0) {
                    bindOrderId = JSON.parseObject(jsonString).getString("data");
                    countDownTime(40);
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtils.d(" ************** updateInfo  failed ");
            }
        });
    }

    public void getSms(String phone, String ticket, String reandstr) {
        Map<String, String> params = new HashMap<>();
        params.put("p", phone);
        if (!StringUtil.isEmpty(ticket)) {
            params.put("t", ticket);
            params.put("r", reandstr);
        } else {
            params.put("x", "tk");
        }
        params.put("appid", Constants.OWN_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(GET_SMS, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {

                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") > 0) {
                    countDownTime(Integer.valueOf(jsonObject.getString("data")));
                } else {
                    Toast.makeText(BankActivity.this, jsonObject.getString("errmsg"), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void bindBankCard() {
        ProgressDialogUtil.startProgressDialog(this);
        Map<String, String> params = new HashMap<>();
        params.put("openid", userInfoBean.getOpenid());
        params.put("token", userInfoBean.getToken());
        params.put("appid", Constants.DATA_APP_ID);
        // params.put("bindOrderId", bindOrderId);
        params.put("verifyCode", etSms.getText().toString());
        params.put("mobile", etBankPhone.getText().toString());
        HttpUtil.getInstance().postDataAsynToNet(BIND_BANK_CARD, params, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                LogUtil.i(jsonString+" ***********  ");
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                if (jsonObject.getInteger("errnum") == 0) {
                    ToastUtils.show("绑卡成功");
                    startActivity(new Intent(BankActivity.this, ExamineFailActivity.class));
                    finish();
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtils.d(" ************** updateInfo  failed ");
            }
        });
    }

    public void updateInfo() {
        ProgressDialogUtil.startProgressDialog(this);
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        IdCardAndBankInfo idCardAndBankInfo = userInfoBean.getDetail();
        idCardAndBankInfo.setBankName(etEtBankName.getText().toString());
        idCardAndBankInfo.setBankNum(etBankNum.getText().toString());
        idCardAndBankInfo.setBankPhone(etBankPhone.getText().toString());
        param.put("detail", JSON.toJSONString(idCardAndBankInfo));

        HttpUtil.getInstance().postDataAsynToNet(UPDATE, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum == 0) {
                    SPUtil.put("userInfo", baseBean.data);
                    ToastUtils.show("绑定成功");
                    EventBus.getDefault().post(new UserInfoEvent());
                    startActivity(new Intent(BankActivity.this,UserInfoActivity.class));
                    finish();
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void countDownTime(int time) {
        /** 倒计时60秒，一次1秒 */
        timer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                tvSendCode.setTextColor(getResources().getColor(R.color.color_3763fe));
                tvSendCode.setText(String.format(getString(R.string.countdown), millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                tvSendCode.setEnabled(true);
                tvSendCode.setTextColor(getResources().getColor(R.color.color_333333));
                tvSendCode.setText("获取验证码");
            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        ProgressDialogUtil.stopProgressDialog();
    }


    private void ocrBankCard(String filePath) {
        Map<String, Object> params = new HashMap<>();
        params.put("api_key", Constants.FACE_ID_API_KEY);
        params.put("api_secret", Constants.FACE_ID_SECRET);
        params.put("image", new File(filePath));
        HttpUtil2.getInstance().postDataAsynToNet(OCR_BANK_CARD, params, new HttpUtil2.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                ProgressDialogUtil.stopProgressDialog();
                JSONObject jsonObject = JSON.parseObject(jsonString);
                LogUtil.i(jsonString + " *********  ");
                if (jsonObject.containsKey("error")) {
                    ToastUtils.show("请拍摄正确的银行卡照片");
                } else {
                    if (jsonObject.getInteger("result") == 1001) {
                        if (StringUtil.isEmpty(jsonObject.getString("name"))) {
                            etBankNum.setText(jsonObject.getString("number"));
                            etEtBankName.setText(jsonObject.getString("bank"));
                        } else {
                            ToastUtils.show("请使用借记卡");
                        }
                    } else {
                        ToastUtils.show("请拍摄清楚的银行卡照片");
                    }
                }
            }

            @Override
            public void failed(Call call, IOException e) {
                LogUtil.i("失败");
            }
        });
    }

}
